package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CachePenetrationProtect;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.Cached;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class JectcacheTestController {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	private ChannelTopic topic = new ChannelTopic("/redis/pubsub");


	/**
	 * 获取缓存中数据
	 * 
	 * @param id
	 * @return
	 */
	@Cached(expire = 60, cacheType = CacheType.BOTH, name = "testCache.", key = "#id")
	@CacheRefresh(refresh = 50, stopRefreshAfterLastAccess = 60)
	@CachePenetrationProtect
	@GetMapping("{id}")
	public Object findbyId(@PathVariable Long id) {
		log.info("Execute findbyId method logic, id [{}]", id);

		Assert.notNull(id, "Id can not be null");

		return id + "------->" + System.currentTimeMillis();
	}

	/**
	 * 更新缓存中数据
	 * 
	 * @param id
	 * @return
	 */
	@CacheUpdate(name = "testCache.", key = "#id", value = "#result")
	@CachePenetrationProtect
	@GetMapping("update/{id}")
	public Object update(@PathVariable Long id) {
		log.info("Execute update method logic, id [{}]", id);

		Assert.notNull(id, "Id can not be null");
		String message = "findbyId:1";
		redisTemplate.convertAndSend(topic.getTopic(),message);
		return id + "------->" + System.currentTimeMillis();
	}

	/**
	 * 删除缓存数据
	 * 
	 * @param id
	 */
	@CacheInvalidate(name = "testCache.", key = "#id")
	@GetMapping("del/{id}")
	public void deleteUser(@PathVariable long id) {
		log.info("Execute del method logic, id [{}]", id);
	}

}
